
import { merge } from 'lodash'
import { Message } from 'element-ui'
import * as util from '@/libs/util'
export default {
  namespaced: true,

  // 如果只做路由级的权限，下面字段都用不到
  state: {
    // 功能编码
    functions: ['normal'],
    routeList: [],
    // 是否管理员
    isAdmin: false,
    once: false
  },
  mutations: {
    set (state, data) {
      state.functions = data.functions
      state.routeList = data.routeList
      // state.routeList = ['/Basic/Area','/Basic/DealerGroup']

      state.isAdmin = data.isAdmin
    }
  },
  actions: {
    clear ({ state }) {
      state.functions = []
      state.routeList = []
      state.once = false
      state.isAdmin = false
    },
    async bindPermission ({ state, commit, dispatch }, data) {
      if (state.once) return state.functions
      else {
        return await new Promise(res => {
          // GET /api/WebMenu/GetMyMenuList 获取我的菜单
          // 同步请求，阻塞ui防止页面抖动
          const request = new XMLHttpRequest()
          request.open('GET', '/api/WebMenu/GetMyMenuList', false)

          request.setRequestHeader('token', localStorage.getItem('token'))
          request.send(null)
          if (request.status === 200) {
            const body = JSON.parse(request.responseText)
            // session 过期跳出
            if (
              body.Code === 'DECODE_SIGNATURE_FAILED' ||
              body.Code === 'DECODE_NULL_ERROR' ||
              body.Code === 'DECODE_OTHER_ERROR'
            ) {
              dispatch('myadmin/account/logout', {}, { root: true })
              return
            } else if (body.Code !== '200') {
              Message({
                message: body.Msg,
                type: 'error',
                duration: 5 * 1000
              })
              return
            }
            let { ShowList, RouteList } = body.Entity
            let functions = state.functions.concat(ShowList),
              routeList = state.routeList.concat(RouteList)

            const userPermissionInfo = merge(
              {
                functions,
                routeList,
                isAdmin: false
              },
              data
            )
            // 设置权限信息
            commit('set', {
              functions: userPermissionInfo.functions,
              routeList: userPermissionInfo.routeList,
              isAdmin: userPermissionInfo.isAdmin
            })
            state.once = true

            res(state.functions)
          }
        })
      }
    }
  }
}
